package www.dianbaozu.com.ui.server

import android.view.View
import androidx.databinding.ObservableField
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import www.dianbaozu.com.R
import www.wen.com.common.lib.base.module.BaseApiViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.data.repository.AppDataManager
import www.wen.com.common.lib.extension.getString


/**
 * @author WEN
 * @Description:创建新的服务器
 * @date 2020//25 17:48
 */
class UpdateServerInfoViewModel @ViewModelInject constructor(appDataManager: AppDataManager) : BaseApiViewModel(appDataManager) {

    val mIsShowErrorTip = ObservableField(View.INVISIBLE)

    val mErrorTipText = ObservableField("")

    /**
     * 创建新的服务器
     */
    fun requestUpdateServerInfo(
        serverId: String,
        body: RequestBodyParameter,
        action: ((ServerUpdateInfoEntity) -> Unit)? = null,
    ) {
        viewModelScope.launch {
            loading.value = UiStateCustom(
                stateData = LoadingDialog(
                    getString(R.string.be_updating),
                    LoadingDialogStateType.LOADING
                )
            )
            val result = appDataManager.requestUpdateServerInfo(serverId,body)
            if (result is Result.Success) {
                loading.value = UiStateCustom(
                    stateData = LoadingDialog(
                        tip = getString(R.string.update_successfully),
                        loadingDialogStateType = LoadingDialogStateType.SUCCESS,
                        isShowDialogTip = false,
                        isShowToastTip = true,
                    )
                )
                action?.invoke(result.data)
            } else if (result is Result.Error) {
                loading.value = UiStateCustom(
                    stateData = LoadingDialog(
                        tip = result.exception.message!!,
                        loadingDialogStateType = LoadingDialogStateType.ERROR,
                        isShowDialogTip = false,
                        isShowToastTip = false
                    )
                )
                mIsShowErrorTip.set(View.VISIBLE)
                mErrorTipText.set(result.exception.message?:getString(R.string.network_anomaly))
            }
        }
    }

}


